﻿using Microsoft.AspNetCore.Mvc;
using Qy.Core;
using Qy.Scenario;
using Qy.Web.Authorize;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Qy.Web.Areas.Api;

[Route("Api/[controller]/[action]")]
[Verify]
public class UserController : Base
{
    private readonly ApplicationContext _applicationContext;
    private readonly UserService _adminUserService;
    private readonly UserGroupService _adminUserGroupService;
    private readonly UserDeptService _adminUserDeptService;
    private readonly UserPostService _adminUserPostService;
    public UserController(
        ApplicationContext applicationContext,
        UserService adminUserService,
        UserGroupService adminUserGroupService,
        UserDeptService adminUserDeptService,
        UserPostService adminUserPostService
        )
    {
        _applicationContext = applicationContext;
        _adminUserService = adminUserService;
        _adminUserGroupService = adminUserGroupService;
        _adminUserDeptService = adminUserDeptService;
        _adminUserPostService = adminUserPostService;
    }
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.User_Index)]
    public async Task<IActionResult> ListAsync([FromQuery] UserQuery query)
    {
        int gid = _applicationContext.ILoginUserInfoMethods.LoginGroupId();//判断普通用户不能看超级管理员
        if (query.ExportExcel)
        {
            PagedInfo<ViewUser> list = await _adminUserService.GetPageListAsync(query, gid);
            string sFileName = ExcelHelperAction.ExportExcel(list.Result, "用户列表");
            return Success(new { FilePath = "/export/" + sFileName, fileName = sFileName });
        }
        else
        {
            PagedInfo<ViewUser> list = await _adminUserService.GetPageListAsync(query, gid);
            return Success(new { data = list.Result, count = list.TotalNum });
        }
    }

    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.UserDept_Index)]
    public async Task<IActionResult> DeptListTreeAsync()
    {
        var pagedList = await _adminUserDeptService.AsUserDeptTree();
        return Success(new { data = pagedList });
    }

    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.User_AddOrEditView)]
    public async Task<IActionResult> AddOrEditAsync(int id)
    {
        int gid = _applicationContext.ILoginUserInfoMethods.LoginGroupId();
        List<UserGroup> userGroups = await _adminUserGroupService.GetListAllAsync();
        if (gid != 1)
            userGroups.RemoveAll(e => e.Id == 1);//只有超级管理员才能添加超级管理员用户
        IEnumerable<CategoryViewModel> userDepts = await _adminUserDeptService.GetUserDeptListAsync();
        List<UserPost> userPosts = await _adminUserPostService.GetAllAsync();
        if (id > 0)
        {
            User user = await _adminUserService.GetIdAsync(id);
            user.PassWord = null;
            return Success(new { data = user, userGroups, userDepts, userPosts });
        }
        return Success(new { userGroups, userDepts, userPosts });
    }
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.User_UserChange)]
    public async Task<IActionResult> UserChangeAsync()
    {
        ViewUser user = await _adminUserService.GetCacheAsync(_applicationContext.ILoginUserInfoMethods.LoginUserId());
        return Success(new { data = user });
    }

    [HttpPut]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.User_UserChangeEdit)]
    [Log(Name = "修改个人信息")]
    public async Task<IActionResult> UserChangePostAsync([FromBody] EditUser editUser)
    {
        int userId = _applicationContext.ILoginUserInfoMethods.LoginUserId();
        if (1 > await _adminUserService.EditUserInfoUpdateAsync(editUser, userId))
            return Fail("修改失败，有可能是旧密码不正确！");
        return Success($"修改个人信息{editUser.UserName}-{editUser.NickName}");
    }

    [HttpPost, ActionName("Create")]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.User_AddOrEdit)]
    [Log(Name = "新增用户")]
    public async Task<IActionResult> CreatePostAsync([FromBody] EditUser user)
    {
        if (string.IsNullOrEmpty(user.PassWord))
            return Fail("新增用户密码不能为空！");
        if (await _adminUserService.GetByUsernameAsync(user.UserName) == false)
            return Fail("该登录名已存在，请重新输入！");
        User adminUser = new()
        {
            GroupId = user.GroupId,
            DeptId = user.DeptId,
            PostId = user.PostId,
            UserName = user.UserName,
            PassWord = MD5Utility.MD5Encrypt32(user.PassWord).ToLower(),
            NickName = user.NickName,
            Status = user.Status
        };
        await _adminUserService.InsertAsync(adminUser);
        return Success("添加成功" + adminUser.UserName);
    }

    [HttpPut, ActionName("Edit")]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.User_AddOrEdit)]
    [Log(Name = "修改用户")]
    public async Task<IActionResult> EditPost([FromBody] EditUser user)
    {
        int res = await _adminUserService.Update(user);
        return res switch
        {
            0 => Fail("编辑失败 Id:" + user.Id + "可能是写入数据库错误"),
            -1 => Fail("请勿非法提交 Id:" + user.Id),
            -2 => Fail("该用户名已存在，请重新输入 Id:" + user.Id),
            _ => Success("成功编辑用户 Id:" + user.Id),
        };
    }
    [HttpPut, ActionName("ChStatus")]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.User_AddOrEdit)]
    [Log(Name = "修改用户状态")]
    public async Task<IActionResult> ChStatus([FromBody] EditUserStatus adminUser)
    {
        if (0 < await _adminUserService.ChStatusUpdateAsync(adminUser))
            return Success("设置为 " + adminUser.Status.ToString() + ", Id:" + adminUser.Id);
        else
            return Fail("设置为 " + adminUser.Status.ToString() + ", Id:" + adminUser.Id);
    }
    [HttpDelete]
    [ActionPermissionFilter(Permission = PermissionKeys.User_Delete)]
    [Log(Name = "删除用户")]
    public async Task<IActionResult> Delete(int id)
    {
        if (await _adminUserService.DeleteDelCache(id) > 0)
            return Success("删除用户 id:" + id);
        else
            return Fail("删除失败！");
    }

}
